package com.fss.home.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyuncs.exceptions.ClientException;
import com.fss.article.domain.Response;
import com.fss.home.domain.*;
import com.fss.home.service.HomeService;
import com.fss.common.core.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;


@RestController
@RequestMapping("/home")
public class HomeController extends BaseController
{
    @Autowired
    private HomeService homeService;

    @GetMapping("/getSwiper")
    public List<Home> getSwiperImages() {
        return homeService.getSwiperImages();
    }
    //获取楼层数据
    @GetMapping("/getGoodList")
    public List<Home> getGoodList() {
        return homeService.getGoodList();
    }
    //获取商品详情
    @GetMapping("/getProductWithImages")
    public List<Product> getProductWithImages() {
        return homeService.getProductWithImages();
    }
    //获取所有品类
    @PostMapping("/getAllCategories")
    public  List<Category2>getAllCategories(){
        return homeService.getAllCategories();
    }
    //品类下的商品
    @GetMapping("getProductList/{cateGoryId}/{sortType}")
    public List<Product> selectCateToProduct(
            @PathVariable long cateGoryId,
            @RequestParam(required = false) Double priceMin,
            @RequestParam(required = false) Double priceMax,
            @PathVariable int sortType) {

        System.out.println("Category ID: " + cateGoryId + ", Sort Type: " + sortType + ", Price Min: " + priceMin + ", Price Max: " + priceMax);
        return homeService.selectCateToProduct(cateGoryId, priceMin, priceMax, sortType);
    }
    //获取商品详情
    @GetMapping("/getProductDetail/{productId}")
    public Product getProductDetail(@PathVariable Long productId) {
            return homeService.getProductDetail(productId);
    }
    //获取商品规格
    @GetMapping("/getProductSku/{productId}")
    public List<ProductSku> getProductSkuByProductId(@PathVariable Long productId) {
        return homeService.getProductSkuByProductId(productId);
    }

    //新增商品
    @PostMapping("/addProduct")
    public void addProduct(@RequestBody Product productEntity) {

        homeService.addProduct(productEntity);
    }
    //模糊查询商品
    @GetMapping("/search")
    public List<Product> searchProducts(@RequestParam("productName") String productName) {
        System.out.println("Searching for products with name: " + productName);
        return homeService.searchProductsByName(productName);
    }
    //删除商品
    @DeleteMapping("/deleteProduct/{productId}")
    public void deleteProduct(@PathVariable Long productId) {
        homeService.deleteProduct(productId);

    }
    //修改商品
    @PutMapping("/updateProduct")
    public void updateProduct(@RequestBody Product product) {

        // 调用服务层进行商品更新
        homeService.updateProduct(product);
    }
    //删除商品图片
    @DeleteMapping("/deleteImage/{imageId}")
    public String deleteImage(@PathVariable Long imageId) {
        try {
            homeService.deleteImage(imageId);
            return "图片删除成功";
        } catch (RuntimeException e) {
            return "图片删除失败: ";
        }
    }
    //获取配送信息
     @GetMapping("/getDelivery/{userId}")
    public List<Delivery> getDeliveryInfoByUserId(@PathVariable Long userId) {
        return homeService.getDeliveryInfoByUserId(userId);
    }
    // 新增配送信息
    @PostMapping("/addDeliveryInfo")
    public Long addDeliveryInfo(@RequestBody Delivery delivery) {
        return homeService.addDeliveryInfo(delivery);
    }

    // 修改配送信息
    @PostMapping("/updateDeliveryInfo")
    public boolean updateDeliveryInfo(@RequestBody Delivery delivery) {
        return homeService.updateDeliveryInfo(delivery);
    }
    // 删除配送信息
    @DeleteMapping("/deleteDeliveryInfo/{deliveryId}")
         public boolean deleteDeliveryInfo(@PathVariable Long deliveryId) {
        return homeService.deleteDeliveryInfo(deliveryId);
    }

    //上传图片
    @PostMapping("/upload")
    public Response uploadImage(@RequestParam("file") MultipartFile file) throws IOException, ClientException {
        String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
        String bucketName = generateUniqueBucketName("demo");
        // 替换为您的 Bucket 区域
        String region = "cn-guangzhou";
        // 创建 OSSClient 实例
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();

        // 1. 创建存储空间（Bucket）
        ossClient.createBucket(bucketName);
        String name= UUID.randomUUID().toString()+".jpg";
        ossClient.putObject(bucketName, name, new ByteArrayInputStream(file.getBytes()));
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, name, HttpMethod.GET);
        Date expiration = new Date(new Date().getTime() + 2*30*24*3600 * 1000L);
        // 通过HTTP GET请求生成签名URL。
        request.setExpiration(expiration);
        URL signedUrl = ossClient.generatePresignedUrl(request);
        // 打印签名URL。
        System.out.println("signed url for getObject: " + signedUrl);
        ossClient.shutdown();


        return new Response(true,signedUrl.toString() );
    }
    public static String generateUniqueBucketName(String prefix) {
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 生成一个 0 到 9999 之间的随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000); // 生成一个 0 到 9999 之间的随机数
        // 连接以形成一个唯一的 Bucket 名称
        return prefix + "-" + timestamp + "-" + randomNum;
    }


}

